package com.jfinal.ext.shrio;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.erp.common.model.SystemUser;

public class ShiroDbRealm extends AuthorizingRealm {
	private static Logger log = LoggerFactory.getLogger(ShiroDbRealm.class);

	public ShiroDbRealm() {
		super();
		setAuthenticationTokenClass(UsernamePasswordToken.class);
	}

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {

		UsernamePasswordToken upToken = (UsernamePasswordToken) authcToken;
		String username = upToken.getUsername();
		if (username == null) {
			log.warn("用户名不能为空");
			throw new AccountException("用户名不能为空");
		}
		SystemUser user = null;
		try {
			user = SystemUser.dao.findUserByLoginName(username);
		} catch (Exception ex) {
			log.warn("获取用户失败\n" + ex.getMessage());
		}
		if (user == null) {
			log.warn("用户不存在");
			throw new UnknownAccountException("用户不存在");
		}
		// if (user.get("sta") == null || user.getInt("sta").equals(1)) {
		// log.warn("用户被禁止使用");
		// throw new UnknownAccountException("用户被禁止使用");
		// }
		log.info("用户【" + username + "】登录成功");
		ShiroPrincipal subject = new ShiroPrincipal(user);
		// List<String> perms = user.getRolesPerm();
		// List<String> rolelist = new ArrayList<String>();// .getRolesCode();

		// subject.setPerms(perms);
		// subject.setRoles(rolelist);
		subject.setAuthorized(true);
		return new SimpleAuthenticationInfo(subject, user.getPassword(),
				getName());
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 获取当前登录的用户名
		ShiroPrincipal subject = (ShiroPrincipal) super
				.getAvailablePrincipal(principals);
		String username = subject.getUsername();
		SystemUser user = SystemUser.dao.findUserByLoginName(username);
		try {
			if (!subject.isAuthorized()) {
				// 根据用户名称，获取该用户所有的权限列表
				// List<String> perms = user.getRolesPerm();
				// List<String> rolelist = user.getRolesPerm();
				// subject.setPerms(perms);
				// subject.setRoles(rolelist);
				subject.setAuthorized(true);
				// log.info("用户【" + username + "】授权初始化成功......");
				// log.info("用户【" + username + "】 角色列表为：" + subject.getRoles());
				// log.info("用户【" + username + "】 权限列表为：" + subject.getPerms());
			}
		} catch (RuntimeException e) {
			throw new AuthorizationException("用户【" + username + "】授权失败");
		}
		// 给当前用户设置权限
		info.addStringPermissions(subject.getPerms());
		info.addRoles(subject.getRoles());
		return info;
	}

}
